package com.weai.service.impl;

import com.weai.dto.TaskOverviewDTO;
import com.weai.dto.TaskOverviewQueryDTO;
import com.weai.entity.Task;
import com.weai.exception.ResourceNotFoundException;
import com.weai.repository.TaskRepository;
import com.weai.service.TaskOverviewService;
import com.weai.util.DateUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务总览服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TaskOverviewServiceImpl implements TaskOverviewService {
    
    private final TaskRepository taskRepository;
    
    /**
     * 查询任务总览列表
     *
     * @param queryDTO 查询参数
     * @return 任务总览列表
     */
    @Override
    public List<TaskOverviewDTO> findTaskOverviews(TaskOverviewQueryDTO queryDTO) {
        log.info("查询任务总览列表，参数: {}", queryDTO);

        // 获取本周和上周的日期范围
        Map<String, LocalDate> dateRange = DateUtils.getCurrentAndLastWeekDateRange();
        LocalDate startOfWeek = dateRange.get("startOfWeek");
        LocalDate endOfWeek = dateRange.get("endOfWeek");
        LocalDate startOfLastWeek = dateRange.get("startOfLastWeek");
        LocalDate endOfLastWeek = dateRange.get("endOfLastWeek");
        
        // 查询当前周期的任务
        List<Task> currentTasks = taskRepository.findByPeriodDateRange(startOfWeek, endOfWeek);
        
        // 查询上一周期的任务
        List<Task> prevTasks = taskRepository.findByPeriodDateRange(startOfLastWeek, endOfLastWeek);
        
        // 按标题分组
        Map<String, Task> prevTaskMap = prevTasks.stream()
                .collect(Collectors.toMap(Task::getTitleIndex, task -> task, (t1, t2) -> t1));
        
        // 构建任务总览DTO
        List<TaskOverviewDTO> result = new ArrayList<>();
        for (Task task : currentTasks) {
            // 根据查询条件过滤
            if (!matchesFilter(task, queryDTO)) {
                continue;
            }
            
            TaskOverviewDTO dto = TaskOverviewDTO.builder()
                    .id(task.getId())
                    .title(task.getTitle())
                    .titleIndex(task.getTitleIndex())
                    .taskType(task.getType())
                    .taskSubType(task.getSubType())
                    .busiDepartment(task.getBusiDepartment())
                    .busiGoal(task.getBusiGoal())
                    .itDepartment(task.getItDepartment())
                    .currentStatus(task.getStatus())
                    .processor(task.getReceiver())
                    .actualProgress(task.getThisWeekPlan())
                    .newIssues(task.getProblems())
                    .nextWeekPlan(task.getNextWeekPlan())
                    .build();
            
            // 查找上周同一任务
            Task prevTask = prevTaskMap.get(task.getTitleIndex());
            if (prevTask != null) {
                dto.setLastWeekStatus(prevTask.getStatus());
                dto.setOriginalPlan(prevTask.getNextWeekPlan());
                dto.setPendingIssues(prevTask.getProblems());
                
                // 判断是否新完成
                dto.setIsNewlyCompleted("done".equals(task.getStatus()) && 
                        !"done".equals(prevTask.getStatus()));
                
                // 非新项目
                dto.setIsNewProject((task.getStatus().equals("inProgress") && prevTask.getStatus().equals("todo")) || (task.getStatus().equals("todo") && prevTask.getStatus().equals("todo")));
            } else {
                // 本周新项目
                dto.setIsNewProject(true);
                dto.setIsNewlyCompleted("done".equals(task.getStatus()));
            }
            
            result.add(dto);
        }
        
        return result;
    }
    
    /**
     * 更新任务总览信息
     *
     * @param overviewDTO 任务总览信息
     * @return 更新后的任务总览信息
     */
    @Override
    @Transactional
    public TaskOverviewDTO updateTaskOverview(TaskOverviewDTO overviewDTO) {
        log.info("更新任务总览信息，ID: {}", overviewDTO.getId());
        
        // 查询当前任务
        Task task = taskRepository.findById(overviewDTO.getId())
                .orElseThrow(() -> new ResourceNotFoundException("任务不存在，ID: " + overviewDTO.getId()));
        
        boolean isBasicFieldUpdated = isBasicFieldUpdated(task, overviewDTO);
        
        // 更新当前任务字段
        updateTaskFields(task, overviewDTO);
        Task updatedTask = taskRepository.save(task);
        
        // 如果修改了基本信息，则更新所有相同标题的任务
        if (isBasicFieldUpdated && task.getTitle() != null) {
            List<Task> relatedTasks = taskRepository.findByTitle(task.getTitle());
            for (Task relatedTask : relatedTasks) {
                if (!Objects.equals(relatedTask.getId(), task.getId())) {
                    updateTaskBasicFields(relatedTask, overviewDTO);
                    taskRepository.save(relatedTask);
                }
            }
        }
        
        // 构建返回结果
        return convertToOverviewDTO(updatedTask);
    }
    
    /**
     * 删除任务
     *
     * @param id 任务ID
     */
    @Override
    @Transactional
    public void deleteTaskOverview(Integer id) {
        log.info("删除任务，ID: {}", id);
        Task task = taskRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("任务不存在，ID: " + id));
        
        taskRepository.delete(task);
    }
    
    /**
     * 判断任务是否符合过滤条件
     *
     * @param task 任务
     * @param queryDTO 查询条件
     * @return 是否符合条件
     */
    private boolean matchesFilter(Task task, TaskOverviewQueryDTO queryDTO) {
        // 类型过滤
        if (queryDTO.getTaskType() != null && !queryDTO.getTaskType().isEmpty() && 
                !queryDTO.getTaskType().equals(task.getType())) {
            return false;
        }
        
        // 子类型过滤
        if (queryDTO.getTaskSubType() != null && !queryDTO.getTaskSubType().isEmpty() && 
                !queryDTO.getTaskSubType().equals(task.getSubType())) {
            return false;
        }
        
        // 业务部门过滤
        if (queryDTO.getBusiDepartment() != null && !queryDTO.getBusiDepartment().isEmpty() && 
                (task.getBusiDepartment() == null || 
                !task.getBusiDepartment().contains(queryDTO.getBusiDepartment()))) {
            return false;
        }
        
        // 业务目标过滤
        if (queryDTO.getBusiGoal() != null && !queryDTO.getBusiGoal().isEmpty() && 
                (task.getBusiGoal() == null || 
                !task.getBusiGoal().contains(queryDTO.getBusiGoal()))) {
            return false;
        }
        
        // IT部门过滤
        if (queryDTO.getItDepartment() != null && !queryDTO.getItDepartment().isEmpty() && 
                (task.getItDepartment() == null || 
                !task.getItDepartment().contains(queryDTO.getItDepartment()))) {
            return false;
        }
        
        // 处理人过滤
        if (queryDTO.getProcessor() != null && !queryDTO.getProcessor().isEmpty() && 
                (task.getReceiver() == null || 
                !task.getReceiver().contains(queryDTO.getProcessor()))) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 判断是否修改了基本字段（需要同步更新相关任务）
     *
     * @param task 当前任务
     * @param dto 更新数据
     * @return 是否修改了基本字段
     */
    private boolean isBasicFieldUpdated(Task task, TaskOverviewDTO dto) {
        return (dto.getTaskType() != null && !dto.getTaskType().equals(task.getType())) ||
               (dto.getTaskSubType() != null && !dto.getTaskSubType().equals(task.getSubType())) ||
               (dto.getBusiDepartment() != null && !Objects.equals(dto.getBusiDepartment(), task.getBusiDepartment())) ||
               (dto.getBusiGoal() != null && !Objects.equals(dto.getBusiGoal(), task.getBusiGoal())) ||
               (dto.getItDepartment() != null && !Objects.equals(dto.getItDepartment(), task.getItDepartment()));
    }
    
    /**
     * 更新任务所有字段
     *
     * @param task 任务
     * @param dto 更新数据
     */
    private void updateTaskFields(Task task, TaskOverviewDTO dto) {
        // 更新基本字段
        updateTaskBasicFields(task, dto);
        
        // 更新进度相关字段
        if (dto.getActualProgress() != null) {
            task.setThisWeekPlan(dto.getActualProgress());
        }
        if (dto.getNewIssues() != null) {
            task.setProblems(dto.getNewIssues());
        }
        if (dto.getNextWeekPlan() != null) {
            task.setNextWeekPlan(dto.getNextWeekPlan());
        }
    }
    
    /**
     * 更新任务基本字段（需要同步更新的字段）
     *
     * @param task 任务
     * @param dto 更新数据
     */
    private void updateTaskBasicFields(Task task, TaskOverviewDTO dto) {
        if (dto.getTaskType() != null) {
            task.setType(dto.getTaskType());
        }
        if (dto.getTaskSubType() != null) {
            task.setSubType(dto.getTaskSubType());
        }
        if (dto.getBusiDepartment() != null) {
            task.setBusiDepartment(dto.getBusiDepartment());
        }
        if (dto.getBusiGoal() != null) {
            task.setBusiGoal(dto.getBusiGoal());
        }
        if (dto.getItDepartment() != null) {
            task.setItDepartment(dto.getItDepartment());
        }
    }
    
    /**
     * 转换为任务总览DTO
     *
     * @param task 任务
     * @return 任务总览DTO
     */
    private TaskOverviewDTO convertToOverviewDTO(Task task) {
        return TaskOverviewDTO.builder()
                .id(task.getId())
                .title(task.getTitle())
                .titleIndex(task.getTitleIndex())
                .taskType(task.getType())
                .taskSubType(task.getSubType())
                .busiDepartment(task.getBusiDepartment())
                .busiGoal(task.getBusiGoal())
                .itDepartment(task.getItDepartment())
                .currentStatus(task.getStatus())
                .processor(task.getReceiver())
                .actualProgress(task.getThisWeekPlan())
                .newIssues(task.getProblems())
                .nextWeekPlan(task.getNextWeekPlan())
                .build();
    }
} 